package com.redis.utils;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.ScanParams;
import redis.clients.jedis.resps.ScanResult;

public class JedisUtils {
	private static String host ="192.168.232.101";
    private static int port =6379;
    private static Jedis jedis=null;
    private int poolsize = 10;
    private static List<Jedis> pool = new LinkedList<>();

    private void initPools() {
        if (pool.size()<=0){
            for (int i = 0; i < poolsize ; i++){
                pool.add(new Jedis(host,port));
            }
        }

    }
    public JedisUtils(){
        jedis =  new Jedis(host,port);
    }
    
    public JedisUtils(int poolsize){
        this.poolsize = poolsize;
        initPools();
    }

    public static Jedis getConnection(String host,int port){
        jedis =  new Jedis(host,port);
        return jedis;
    }
    
    public static Jedis getConnection() {
        jedis =  pool.get(new Random().nextInt(pool.size()));
        return jedis;
    }

    public void close() {
        if(jedis !=null){
            jedis.close();
        }
    }
    
    public void setString(String key ,String value){
        if(jedis == null ){
            getConnection();
        }
        jedis.set(key,value);
    }
    
    public String getString(String key) {
    	if(jedis == null ){
    		getConnection();
    	}
    	return jedis.get(key);
    }
    
    public Set<String> keys(String keyPrefix) {// = keys "keyPrefix*"
    	if(jedis == null ){
    		getConnection();
    	}
    	return jedis.keys(keyPrefix+"*");
    }
    
    public Set<String> scan(String keyPrefix) {// = scan 0 MATCH keyPrefix*
    	if(jedis == null ){
    		getConnection();
    	}
    	String cursor = ScanParams.SCAN_POINTER_START;
        ScanParams scanParams = new ScanParams();
        scanParams.match(keyPrefix+"*");// keyPrefix*
//        scanParams.count(1000); // = scan 0 MATCH keyPrefix* COUNT 1000
        Set<String> set = new HashSet<String>();
        while (true){
            //使用scan命令获取数据，使用cursor游标记录位置，下次循环使用
            ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
            cursor = scanResult.getCursor();// 返回0 说明遍历完成
            List<String> list = scanResult.getResult();
            for(int m = 0;m < list.size();m++){
                String mapentry = list.get(m);
                set.add(mapentry);
            }
            if ("0".equals(cursor)){
                break;
            }
        }
		return set;
	}
}
